package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Business;
import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.util.FileUploadUtil;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private IBusinessService businessService;

    //处理查询所有的请求 /business/list
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") BusinessQueryObject qo){
        PageInfo<Business> pageInfo = businessService.query(qo);//查出数据
        model.addAttribute("pageInfo",pageInfo);
        //model拿到数据后与jsp合并渲染成HTML格式，展现在页面上
        return "business/list";  // /WEB-INF/views/business/list.ftl
    }

    @RequestMapping("/input")
    public String input(Model model,Long id){
        if (id != null){
            Business business = businessService.get(id);
            model.addAttribute("business",business);
        }


        return "/business/input";
    }




    @RequiredPermission(name = "门店删除", expression = "business/delete")
    //处理删除请求 /business/delete?id=1
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id!=null) {
            businessService.delete(id);
        }
        return "redirect:/business/list";  //localhost/business/list
    }

    @RequiredPermission(name = "门店新增/修改", expression = "business/saveOrUpdate")
    //处理保存或者修改请求请求 /business/saveOrUpdate  //参数在请求体中，操作input界面的提交功能
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file, HttpServletRequest request) throws Exception {

        //图片处理
        if (file !=null&& file.getSize()>0){
            String path = request.getServletContext().getRealPath("/");
            String filePath = FileUploadUtil.uploadFile(file, path);
            business.setLicenseImg(filePath);
        }


        if (business.getId()==null) {
            businessService.save(business);
        }else{
            businessService.update(business);
        }
        return "redirect:/business/list";  //localhost/business/list
    }
}
